import { defineStore, type StateTree } from "pinia";
import { v4 as uuidv4 } from "uuid";

const useChatState = () => {
  const chatMap = ref<ChatMap>(
    new Map([[0, { id: 0, name: "_blank", messages: {}, show: false }]])
  );
  const currentChat = ref<string | number>(0);
  return {
    chatMap,
    currentChat,
  };
};
export const chatStore = defineStore(
  "chatStore",
  () => {
    const chatState = useChatState();
    const { chatMap, currentChat } = chatState;
    const getChatMap = () => {
      return chatMap;
    };
    const clearChatList = () => {
      chatMap.value.clear();
    };
    const getChat = (id: string | number) => {
      return chatMap.value.get(id);
    };
    const setChat = (id?: string, value?: Chat) => {
      const randomId = uuidv4();
      const chat = {
        id: randomId,
        name: "未命名",
        messages: {},
      };
      chatMap.value.set(id ? id : randomId, value ? value : chat);
      return value ? value : chat;
    };
    const addChatMessages = (chatId: string | number, message: Message) => {
      const messageId = uuidv4();
      chatMap.value.get(chatId)!.messages[messageId] = {
        ...message,
        id: messageId,
        createdAt: Date.now().toString(),
        updatedAt: Date.now().toString(),
      };

      return messageId;
    };
    const deleteChat = (id: string) => {
      chatMap.value.delete(id);
    };
    const setCurrentChat = (value: string | number) => {
      currentChat.value = value;
    };
    const getCurrentChat = () => {
      return currentChat;
    };
    return {
      ...chatState,
      getChatMap,
      addChatMessages,
      getChat,
      setChat,
      clearChatList,
      deleteChat,
      setCurrentChat,
      getCurrentChat,
    };
  },
  {
    persist: persist(),
  }
);
